import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Query } from 'react-apollo'
import InviteMember from 'graphql/user/newOrgMember.graphql'
import QueryUsers from 'graphql/user/queryUser.graphql'
import GetSubTeams from 'graphql/user/getSubTeams.graphql'
import QueryAllMembers from 'graphql/user/queryAllOrgMembers.graphql'
import { Header, Image } from 'semantic-ui-react'
import {
  Form as FormTable,
  Section as TableSection,
  Switch,
  Submit,
  MultiSwitch,
  SearchInput,
} from 'components/tableForm'
import { global as globalDuck } from 'ducks'

const getVariables = (values) => {
  const result = {}
  if (values.name) result.name = values.name.value.name
  if (values.name) result.userId = values.name.value.id
  if (values.role) result.role = values.role.value
  if (values.subTeam) {
    result.subTeam = Object.keys(values.subTeam.value).reduce((pre, next) => {
      if (values.subTeam.value[next]) pre.push(next)
      return pre
    }, [])
  }
  return result
}

const getOptions = (addedUsersData) => {
  const reducedMember = addedUsersData.org_member.map(member => member.user_id)
  return queryUsersData => queryUsersData.user.reduce((pre, next) => {
    const isAdded = reducedMember.includes(next.id) > 0
    pre.push({
      disabled: isAdded,
      text: next.name,
      value: next,
      content: (
        <Header as="h5" style={{ marginTop: '0' }}>
          <Image src={next.avatar} />
          <Header.Content>{next.name}</Header.Content>
        </Header>
      ),
      description: isAdded ? '已经添加' : '',
      icon: isAdded
        ? null
        : {
          name: 'add',
          className: 'right floated',
          color: 'green',
        },
    })
    return pre
  }, [])
}

class newDataset extends Component {
  componentDidMount = () => {}

  render() {
    const { match, org } = this.props
    const orgId = org.owner_object.id
    const orgName = org.owner_object.name
    const returnUrl = `/org/${orgName}/user/members/list`
    return (
      <Query query={QueryAllMembers} variables={{ ownerId: orgId }}>
        {({ loading, error, data }) => {
          if (loading) return 'Loading....'
          if (error) return `Error! ${error.message}`
          return (
            <FormTable>
              <TableSection header="邀请成员">
                <SearchInput
                  name="name"
                  header="搜索成员"
                  description="请输入成员的名称或者邮箱"
                  query={{
                    query: QueryUsers,
                    variables: {},
                    getData: getOptions(data),
                  }}
                />
                <Switch
                  name="role"
                  header="选择该成员的角色"
                  description="管理员角色拥有组织的全部权限"
                  options={[
                    { name: 'member', value: '普通成员' },
                    { name: 'admin', value: '管理员' },
                  ]}
                />
                <MultiSwitch
                  name="subTeam"
                  header="子组织"
                  description="同时邀请该成员加入子组织"
                  query={{
                    query: GetSubTeams,
                    variables: { ownerId: orgId },
                    getData: (data) => {
                      if (!data && !data.team_member) return []
                      return data.team_member.map(member => ({ name: member.id, value: member.name }))
                    },
                  }}
                />
              </TableSection>
              <Submit
                submit={{
                  text: '邀请',
                  variables: { ownerId: orgId },
                  getVariables,
                  mutation: InviteMember,
                  success: data => returnUrl,
                }}
                cancle={{ text: '取消', url: returnUrl }}
                redirect
              />
            </FormTable>
          )
        }}
      </Query>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(newDataset)
